package com.foreveross.chameleon.exhibition;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.View;
import android.webkit.WebView;
import android.widget.TextView;
import com.foss.base.BslConfig;
import com.foss.utils.*;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by wzq on 14-8-19
 */
public class ActivityEntry extends Activity {
    private Context mCtx;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_entry);
        mCtx = this;
        tvProgress = (TextView) findViewById(R.id.tv_progress);

        //
        new Thread(new Runnable() {
            @Override
            public void run() {
                check();
                init();
                sendToUiThread(new Runnable() {
                    @Override
                    public void run() {
                        initDone();
                    }
                });
            }
        }).start();
    }

    // just test TODO to be delete
    private void check() {
        sendToUiThread("检测状态...");
        StringBuilder sb = new StringBuilder();
        sb.append("\nfirst installation = " + SpTool.getSp().getBoolean(BslConfig.SP_KEY_FIRST_INSTALL, true));
        sb.append("\nwww folder exist = " + new File(BslConfig.WWW_FOLDER_IN_SD).exists());
        // sandbox 模式
        sb.append("\nsandbox mod =" + getResources().getString(R.string.build_config_sandbox));
        // 读取prop文件
        sb.append("\nAES_PASSWORD from prop =" + PropReader.getInstance().getProp("AES_PASSWORD"));
        // AES_PASSWORD
        sb.append("\nAES_PASSWORD from java = " + BslConfig.AES_PASSWORD);
        // 客户端 加密测试
        String str = "你好@#$%^&*";
        String encryptStr = AesTool.getInstance().encryptString(str);
        String decryptStr = AesTool.getInstance().decryptString(encryptStr);
        if (str.equals(decryptStr)) {
            sb.append("\n客户端 加解密String ok");
        } else {
            sb.append("\n客户端 加解密String 失败");
        }
        // 脚本加密，java解密
        AssetManager assetManager = getAssets();
        String deStr = null;
        try {
            InputStream src = assetManager.open("www/test_crypt.txt");
            InputStream dst = AesTool.getInstance().decryptStream(src);
            if (dst != null) {
                deStr = IOUtils.stream2String(dst, "UTF-8");
            } else {
                sb.append("\ndecryptStream fail");
            }

        } catch (IOException e) {
            e.printStackTrace();
            sb.append("\n test_crypt.txt不存在");
        }
        if (deStr == null) {
            sb.append("\n test_crypt.txt解密失败");
        } else {
            sb.append("\n test_crypt.txt解密 =" + deStr);
        }
        // folder位置
        sb.append("\nwww folder = " + BslConfig.WWW_FOLDER_IN_SD);
        // provider
        sb.append("\nproviderName = " + getResources().getString(R.string.providerName));
        sb.append("\nproviderAuth = " + getResources().getString(R.string.providerAuth));

        // 打印输出
        final String checkInfo = sb.toString();
        sendToUiThread(new Runnable() {
            @Override
            public void run() {
                TextView tvCheck = (TextView) findViewById(R.id.tv_check);
                tvCheck.setText(checkInfo);
            }
        });
        AppLog.i(checkInfo);
    }

    private void init() {
        sendToUiThread("初始化...");
        if (!BslConfig.IS_SANDBOX) {
            // we shall do nothing
            AppLog.i(" not sandbox mod ");
            return;
        }

        // sandbox mode : copy and update
        AppLog.i("sandbox mod ");
        sendToUiThread("拷贝文件...");
        boolean isFirst = SpTool.getSp().getBoolean(BslConfig.SP_KEY_FIRST_INSTALL, true);
        boolean isCopyAll = isFirst || !new File(BslConfig.WWW_FOLDER_IN_SD).exists();
        if (isCopyAll) {
            AppLog.i("copyAll,isFirst=" + isFirst + ",wwwFolder=" + BslConfig.WWW_FOLDER_IN_SD);
            ActivityEntryAssit.copyAll(mCtx);
        } else {
            int preSavedVer = SpTool.getSp().getInt(BslConfig.SP_KEY_APPVERSION, 0);
            int currVer = AndroidTool.getVersionCode();
            AppLog.i("preSavedVer=" + preSavedVer + ",currVer=" + currVer);
            boolean isUpdateCopy = currVer > preSavedVer;
            if (isUpdateCopy) {
                AppLog.i("copyByVersion");
                ActivityEntryAssit.copyByVersion(mCtx);
            } else {
                AppLog.i("do not neet copy anything");
            }
        }
    }

    private void initDone() {
        sendToUiThread("初始化 over");
        // 测试provider
        WebView webView = (WebView) findViewById(R.id.web_test);
        if (BslConfig.IS_SANDBOX) {
            String url1 = BslConfig.SCHEME_PROVIDER + BslConfig.WWW_FOLDER_IN_SD + "/index.html";
            webView.loadUrl(url1);
        } else {
            String url2 = BslConfig.SCHEME_PROVIDER + "/" + BslConfig.ASSETS_WWW_FOLDER + "/index.html";
            webView.loadUrl(url2);
        }


        // record all
        SpTool spTool = SpTool.getSp();
        spTool.write(BslConfig.SP_KEY_FIRST_INSTALL, false);
        spTool.write(BslConfig.SP_KEY_APPVERSION, AndroidTool.getVersionCode());
        findViewById(R.id.pb_init).setVisibility(View.INVISIBLE);

        View btnInitDone = findViewById(R.id.btn_init_done);
        btnInitDone.setVisibility(View.VISIBLE);
        btnInitDone.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(mCtx, chameleon.class);
                mCtx.startActivity(intent);
                finish();
            }
        });

        // 启动mdm
        // MdmCmdExecutor.getInstance().active((Activity) mCtx);
    }


//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (requestCode == MdmCmdExecutor.REQUEST_CODE_MDM) {
//            if (resultCode == RESULT_OK) {
//                AppLog.i("mdm 激活成功");
//            } else {
//                AppLog.i("mdm 未激活");
//                Toast.makeText(mCtx, "mdm 未激活，不允许使用本APP", Toast.LENGTH_SHORT).show();
//                finish();
//            }
//        }
//    }

    private void sendToUiThread(final String str) {
        uiHandler.post(new Runnable() {
            @Override
            public void run() {
                tvProgress.setText(str);
            }
        });
    }

    private void sendToUiThread(Runnable r) {
        uiHandler.post(r);
    }

    private TextView tvProgress;
    private Handler uiHandler = new Handler(Looper.getMainLooper());
}
